import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: () => import('@/views/layout'),
    redirect: '/home',
    children: [
    // 侧边栏导航
      {
        path: 'home',
        component: () => import('@/views/home')
      },
      {
        path: 'user-info',
        component: () => import('@/views/user/userInfo')
      },
      {
        path: 'user-avatar',
        component: () => import('@/views/user/userAvatar')
      },
      {
        path: 'user-pwd',
        component: () => import('@/views/user/userPwd')
      },
      {
        path: 'art-cate',
        component: () => import('@/views/article/artCate')
      },
      {
        path: 'art-list',
        component: () => import('@/views/article/artList')
      }
    ]
  },
  {
    path: '/reg',
    component: () => import('@/views/register')
  },
  {
    path: '/login',
    component: () => import('@/views/login')
  }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/login', '/reg']

// 全局前置路由守卫 在路由守卫里获取路由信息
// 浏览器第一次打开项目页面，会触发一次全局前置路由守卫函数
router.beforeEach((to, from, next) => {
  // console.log(to, from)
  const token = store.state.token
  if (token) {
    // 登录了
    if (!store.state.userInfo.username) {
    // 本地有token值 并且vuex里没有username 才去请求用户信息
    // 防止在切换主页面的其他页面时候也调用这个函数
      store.dispatch('getUserInfoActions')
    }
    next()
  } else {
    // 未登录
    if (whiteList.includes(to.path)) {
      // 未登录，可以访问的路由地址，则放行
      next()
    } else {
      // next()强制切换到登录路径上
      next('/login')
    }
    // next()强制切换到登录路径上
    // next('/login') 这样会导致递归死循环
  }
})

export default router
